<template>
  <div class="z-pagination" v-if="numbers > 1" v-bind="$attrs">
    <component :is="pre" class="z-pagination-button z-pre-page" :class="{'disabled': currentNumber === 1}" @click="handlePre">上一页</component>
    <ul class="z-pagination-box">
      <li v-for="i in numbers" :key="i" :class="{'active': i == currentNumber}" @click="handleChangePageNum(i)">{{ i }}</li>
    </ul>
    <component :is="next" class="z-pagination-button z-next-page" :class="{'disabled': currentNumber === numbers}" @click="handleNext">上一页</component>
  </div>
</template>

<script setup lang="ts" name="ZPagination">
import type { PropType } from 'vue'
import type { ZPagination } from '@/types/zui/zui';

const pre = defineAsyncComponent(()=>import('~icons/material-symbols/chevron-left-rounded'));
const next = defineAsyncComponent(()=>import('~icons/material-symbols/chevron-right-rounded'));
const emits = defineEmits(['change', 'update:pagination']);
const props = defineProps({
  pagination: {
    type: Object as PropType<ZPagination>,
    default: {
      total: 0,
      pageSize: 20,
      pageNum: 1
    }
  },
  query: {
    type: Function,
    default: ()=>{}
  }
});

const data:any = reactive({
  numbers: computed(()=> Math.ceil(props.pagination.total / props.pagination.pageSize)),
  currentNumber: props.pagination.pageNum
});

const {
  numbers,
  currentNumber
} = toRefs(data);


const handlePre = () => {
  if(currentNumber.value <= 1){
    return false;
  }
  const value = {
    total: props.pagination.total,
    pageSize: props.pagination.pageSize,
    pageNum: --currentNumber.value
  };
  emits('update:pagination', value);
  emits('change', value);
  props.query();
}

const handleNext = () => {
  if(currentNumber.value >= numbers.value){
    return false;
  }
  const value = {
    total: props.pagination.total,
    pageSize: props.pagination.pageSize,
    pageNum: ++currentNumber.value
  };
  emits('update:pagination', value);
  emits('change', value);
  props.query();
}

const handleChangePageNum = (index: number) => {
  currentNumber.value = index;
  const value = {
    total: props.pagination.total,
    pageSize: props.pagination.pageSize,
    pageNum: currentNumber.value
  };
  emits('update:pagination', value);
  emits('change', value);
  props.query();
}


defineExpose({
});
</script>

<style lang="scss" scoped>
.z-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 30px;
  line-height: 30px;
  color: var(--z-font-anti);
  .z-pagination-button{
    cursor: pointer;
    font-size: 20px;
    &.disabled{
      cursor: no-drop;
      cursor: not-allowed;
    }
  }
  .z-pagination-box{
    display: flex;
    margin: 0 20px;
    li{
      font-size: 13px;
      min-width: 30px;
      height: 28px;
      line-height: 28px;
      text-align: center;
      cursor: pointer;
      font-weight: bold;
      &.active{
        color: var(--z-bg-btn);
      }
    }
  }
}
</style>
